// 获取用户地址列表
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  try {
    // 查询用户的所有地址，按默认地址和创建时间排序
    const result = await db.collection('addresses')
      .where({
        userId: userOpenid
      })
      .orderBy('isDefault', 'desc')
      .orderBy('createdAt', 'desc')
      .get()

    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    return {
      success: false,
      message: '获取地址列表失败',
      error: error.message
    }
  }
}